package com.mingke.db.Service;

import cn.hutool.core.util.CharsetUtil;
import com.mingke.db.Entity.SchemaTableColumn;
import com.mingke.db.Utils.PropertiesReader;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;

@Service
public class TestService {

    @Autowired
    PropertiesReader propertiesReader;

    public void doGenerateCode(String tableName, List<SchemaTableColumn> columns) throws FileNotFoundException {
        //根据数据表名称生成实体类名
        String className = propertiesReader.capitalFirstLetter(tableName.split("_")[1]);
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        //设置将要填充到模版中的通用数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("package", propertiesReader.basePackage);
        map.put("author", propertiesReader.author);
        map.put("ClassName", className);
        //开始遍历生成Entity,Mapper,Service,Controller
        for(String suffix : propertiesReader.suffixs){
            Template tpl = Velocity.getTemplate("template/"+suffix+"Model.java.vm", CharsetUtil.UTF_8);
            if(suffix.equals("Entity")){
                List<Map<String, Object>> userColumns = new ArrayList<>();
                for(SchemaTableColumn column : columns){
                    HashMap<String, Object> columnMap = new HashMap<>();
                    columnMap.put("columnType", propertiesReader.mysqlTypes().get(column.getDATA_TYPE()));
                    columnMap.put("columnName", column.getCOLUMN_NAME());
                    columnMap.put("comment", column.getCOLUMN_COMMENT());
                    userColumns.add(columnMap);
                }
                map.put("columns", userColumns);
            }
            //生成文件
            VelocityContext vc = new VelocityContext(map);
            //判断对应文件夹如果不存在就新建对应文件夹
            File file = new File(propertiesReader.filePath+suffix);
            if(!file.exists()) {
                file.mkdir();
            }
            //生成文件
            PrintWriter pw = new PrintWriter(propertiesReader.filePath+suffix+"/"+className+suffix+".java");
            //开始渲染模版，生成指定文件
            tpl.merge(vc, pw);
            pw.flush();
            pw.close();
        }
    }
}
